import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import Want from '@ohos.app.ability.Want';
import formInfo from '@ohos.app.form.formInfo';
import formProvider from '@ohos.app.form.formProvider';
import axios, { AxiosError, AxiosResponse } from '@ohos/axios';

export default class EntryFormAbility extends FormExtensionAbility {
  onAddForm(want: Want) {
    // Called to return a FormBindingData object.
    let formData = '';
    return formBindingData.createFormBindingData(formData);
  }

  onCastToNormalForm(formId: string) {
    // Called when the form provider is notified that a temporary form is successfully
    // converted to a normal form.
  }

  onUpdateForm(formId: string) {
    // Called to notify the form provider to update a specified form.
  }

  onChangeFormVisibility(newStatus: Record<string, number>) {
    // Called when the form provider receives form events from the system.
  }

  onFormEvent(formId: string, message: string) {
    // Called when a specified message event defined by the form provider is triggered.
    console.info(`FormAbility onFormEvent, formId = ${formId}, message: ${JSON.stringify(message)}`);

    // 发送一个get请求
    axios<string, AxiosResponse<string>, null>({
      method: "get",
      url: 'https://api.shadiao.pro/chp'
    }).then((res: AxiosResponse) => {
      console.info('result:' + JSON.stringify(res.data));
      class FormDataClass{
        detail: string = res.data.data.text // 和卡片布局中对应
      }
      let formData = new FormDataClass();
      let formInfo: formBindingData.FormBindingData = formBindingData.createFormBindingData(formData);
      formProvider.updateForm(formId, formInfo).then(() => {
        console.info('FormAbility updateForm success.');
      });
    }).catch((error: AxiosError) => {
      console.error(error.message);
    })
  }

  onRemoveForm(formId: string) {
    // Called to notify the form provider that a specified form has been destroyed.
  }

  onAcquireFormState(want: Want) {
    // Called to return a {@link FormState} object.
    return formInfo.FormState.READY;
  }
};